package com.hl.card.modular.system.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hl.card.common.constant.factory.MutiStrFactory;
import com.hl.card.common.exception.BizExceptionEnum;
import com.hl.card.common.exception.BussinessException;
import com.hl.card.common.persistence.dao.SysDicMapper;
import com.hl.card.common.persistence.dao.SysDicTypeMapper;
import com.hl.card.common.annotion.DataSource;
import com.hl.card.common.constant.DSEnum;
import com.hl.card.common.exception.BizExceptionEnum;
import com.hl.card.common.exception.BussinessException;
import com.hl.card.common.persistence.dao.SysDicMapper;
import com.hl.card.common.persistence.dao.SysDicTypeMapper;
import com.hl.card.common.persistence.model.SysDic;
import com.hl.card.common.persistence.model.SysDicType;
import com.hl.card.common.persistence.model.TextUser;
import com.hl.card.common.util.PinYinUtil;
import com.hl.card.modular.system.dao.SysDicDao;
import com.hl.card.modular.system.service.ISysDicService;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.hl.card.common.constant.factory.MutiStrFactory.*;

@Service
@Transactional
public class SysDicServiceImpl implements ISysDicService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Resource
    SysDicTypeMapper sysDicTypeMapper;

    @Resource
    SysDicMapper sysDicMapper;

    @Resource
    SysDicDao sysDicDao;

	@Autowired
	private MongoTemplate mongoTemplate;
	
	private static String COLLECTION_NAME = "config";
	
    @Override
    //@DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    public void addDict(String dictName,String disTypeNo, String dictValues) {
        String typeNo="";
        if(StringUtils.isNotEmpty(disTypeNo)){
           typeNo=disTypeNo;
        }else {
            typeNo= PinYinUtil.getFullSpell(dictName);
        }
        //判断有没有该字典
        List<SysDicType> dicts = sysDicTypeMapper.selectList(new EntityWrapper<SysDicType>().eq("dic_type_no", typeNo));
        if(dicts != null && dicts.size() > 0){
            throw new BussinessException(BizExceptionEnum.DICT_EXISTED);
        }

        //解析dictValues
        List<Map<String, String>> items = MutiStrFactory.parseThreeKeyValue(dictValues);

        //添加字典
        SysDicType dicType=new SysDicType();
        dicType.setDicTypeName(dictName);
        dicType.setDicTypeNo(typeNo);
        dicType.setSystemNo("pc");
        this.sysDicTypeMapper.insert(dicType);

        //添加字典条目
        for (Map<String, String> item : items) {
            String code = item.get(MutiStrFactory.MUTI_STR_KEY);
            String value = item.get(MutiStrFactory.MUTI_STR_VALUE);
            String name = item.get(MutiStrFactory.MUTI_STR_NOTES);
            SysDic sysDic=new SysDic();
            sysDic.setDicTypeNo(typeNo);
            sysDic.setDicNo(code);
            sysDic.setDicValue(value);
            sysDic.setDicNotes(name);
            if("disUserType".equals(name)){
                sysDic.setDicOrder(Integer.parseInt(typeNo));
            }
            this.sysDicMapper.insert(sysDic);
            redisTemplate.opsForHash().put(typeNo, code, value);
        }
    }

    @Override
    //@DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    public void editDict(Integer dictId, String dictName,String disTypeNo, String dicts) {
        //删除之前的字典
        this.delteDict(dictId);

        //重新添加新的字典
        this.addDict(dictName,disTypeNo,dicts);
//        List<Map<String, Object>> list = selectListByCode(disTypeNo);
//        for(Map<String, Object> map:list) {
//            redisTemplate.opsForHash().put(disTypeNo, (String) map.get("dicNo"), (String) map.get("dicValue"));
//        }
    }
    @Override
    //@DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    public void delteDict(Integer dictId) {

        SysDicType dict = sysDicTypeMapper.selectById(dictId);
        //删除这个字典的子词典
        Wrapper<SysDic> dicEntityWrapper = new EntityWrapper<>();
        dicEntityWrapper = dicEntityWrapper.eq("dic_type_no", dict.getDicTypeNo());
        sysDicMapper.delete(dicEntityWrapper);

        //删除这个词典

        sysDicTypeMapper.deleteById(dictId);
    }

    @Override
    //@DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    public List<Map<String, Object>> selectListByCode(String code) {
        List<Map<String, Object>> list=  sysDicDao.selectListByCode(code);
        return list;
    }

    @Override
    //@DataSource(name = DSEnum.DATA_SOURCE_BIZ)
    public Map<String, Object> selectListByCodeNo(String code, String no) {
        return sysDicDao.selectListByCodeNo(code,no);
    }

	@Override
	public void editConfig(Integer dictId, String dictName, String disTypeNo,
			String dicts) {
	      //删除之前的字典
        this.delteDict(dictId);

        //重新添加新的字典
        this.addConfig(dictName,disTypeNo,dicts);
		
	}
	
	 public void addConfig(String dictName,String disTypeNo, String dictValues) {
	        String typeNo="";
	        if(StringUtils.isNotEmpty(disTypeNo)){
	           typeNo=disTypeNo;
	        }else {
	            typeNo= PinYinUtil.getFullSpell(dictName);
	        }
	        //判断有没有该字典
	        List<SysDicType> dicts = sysDicTypeMapper.selectList(new EntityWrapper<SysDicType>().eq("dic_type_no", typeNo));
	        if(dicts != null && dicts.size() > 0){
	            throw new BussinessException(BizExceptionEnum.DICT_EXISTED);
	        }

	        //解析dictValues
	        List<Map<String, String>> items = MutiStrFactory.parseThreeKeyValue(dictValues);

	        //添加字典
	        SysDicType dicType=new SysDicType();
	        dicType.setDicTypeName(dictName);
	        dicType.setDicTypeNo(typeNo);
	        dicType.setSystemNo("pc");
	        this.sysDicTypeMapper.insert(dicType);
	        Update update=new Update();
	        //添加字典条目
	        for (Map<String, String> item : items) {
	            String code = item.get(MutiStrFactory.MUTI_STR_KEY);
	            String value = item.get(MutiStrFactory.MUTI_STR_VALUE);
	            String name = item.get(MutiStrFactory.MUTI_STR_NOTES);
	            SysDic sysDic=new SysDic();
	            sysDic.setDicTypeNo(typeNo);
	            sysDic.setDicNo(code);
	            sysDic.setDicValue(value);
	            sysDic.setDicNotes(name);
	            if("disUserType".equals(name)){
	                sysDic.setDicOrder(Integer.parseInt(typeNo));
	            }
	            if(code.equals("app_url"))
	            {
	           	 update.set("configChilds.$.default_url", value);
				 update.set("configChilds.$.app_url", value);
	            }else if(code.equals("web_url"))
	            {
	             update.set("configChilds.$.web_url", value);
	            }
	            this.sysDicMapper.insert(sysDic);
	        }
	        Query query = Query.query(Criteria.where("configType").is("menuList").and("configChilds.url").is(disTypeNo));
		    mongoTemplate.updateFirst(query, update, TextUser.class,COLLECTION_NAME); 
	    }
}
